<template>
  <div class="users-base-wrapper">
    <!-- 💭主要部分 -->
    <main class="user_main_part">
      <!-- 按钮 -->
      <section>
        <el-button size="mini" @click="handleRefresh" type="primary" icon="el-icon-refresh">刷新</el-button>
        <el-button size="mini" @click="handleAdd" icon="el-icon-plus" type="primary">新增</el-button>
      </section>
      <!-- 表格 -->
      <section class="solution_table_part">
        <el-table :header-cell-style="{ background: 'rgba(117, 60, 202, 0.04)' }" :stripe="true" :data="tableData">
          <el-table-column type="index" width="50"> </el-table-column>
          <!-- 查看 -->
          <!-- <el-table-column align="center" width="40">
            <template v-slot="{ row }">
              <span style="cursor: pointer;">
                <i class="el-icon-view" @click="handleView(row)"></i>
              </span>
            </template>
          </el-table-column> -->
          <!-- 编辑 -->
          <el-table-column align="center" width="40">
            <template v-slot="{ row }">
              <span style="cursor: pointer">
                <i class="el-icon-edit" @click="handleEdit(row)"></i>
              </span>
            </template>
          </el-table-column>
          <!-- 删除 -->
          <el-table-column align="center" width="40">
            <template v-slot="{ row }">
              <span style="cursor: pointer">
                <i class="el-icon-delete" @click="handleDelete(row)"></i>
              </span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="研究代码">
            <template>
              <span>{{ projectCode }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="方案版本号" prop="schemeNum"></el-table-column>
          <el-table-column align="center" label="eCRF版本号" prop="versionNum"></el-table-column>
          <el-table-column align="center" label="eCRF版本日期" prop="versionTime"></el-table-column>
          <el-table-column align="center" label="使用情况" prop="isUsed">
            <template v-slot="{ row }">
              <el-tag type="success" v-if="row.isUsed === 1">已使用</el-tag>
              <el-tag type="danger" v-if="row.isUsed === 0">未使用</el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" label="备注" prop="remark"></el-table-column>
        </el-table>
      </section>
    </main>
    <!-- 💭新增弹窗 -->
    <el-dialog :visible="diaVis" :title="diaTitle" width="600px" @close="handleCancel">
      <el-form label-width="100px" ref="formRef" :model="formData" :rules="formRules">
        <el-form-item v-for="item in formColumns" :key="item.prop" :label="item.label" :prop="item.prop">
          <!-- 下拉框 -->
          <el-select size="mini" style="width: 90%" v-if="item.ele === 'select'" v-model="formData[item.prop]">
            <el-option v-for="it in item.options" :key="it.value" :label="it.label" :value="it.value"></el-option>
          </el-select>
          <!-- 输入框 -->
          <el-input size="mini" style="width: 90%" v-if="item.ele === 'input'" v-model="formData[item.prop]"></el-input>
          <!-- 文本框 -->
          <el-input
            size="mini"
            style="width: 90%"
            type="textarea"
            v-if="item.ele === 'textarea'"
            v-model="formData[item.prop]"
          ></el-input>
          <!-- 时间选择器 -->
          <el-date-picker
            size="mini"
            style="width: 90%"
            v-if="item.ele === 'time'"
            v-model="formData[item.prop]"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="handleCancel">取 消</el-button>
        <el-button size="mini" type="primary" @click="handleConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 弹窗表单的中文和属性名enums
import { mapActions } from 'vuex'
const diaFormItemEnums = {
  schemeId: '方案版本号',
  versionNum: 'ecrf版本号',
  versionTime: '版本时间',
  remark: '备注',
}

// 💭修改时，对比新旧数据
const findDifferentProperties = (oldObj, newObj) => {
  const differentProperties = []
  for (const key in oldObj) {
    // eslint-disable-next-line no-prototype-builtins
    if (oldObj.hasOwnProperty(key) && newObj.hasOwnProperty(key)) {
      if (oldObj[key] !== newObj[key]) {
        differentProperties.push({
          key: diaFormItemEnums[key],
          oldValue: oldObj[key],
          newValue: newObj[key],
        })
      }
    } else {
      // 如果其中一个对象不包含另一个对象的属性，则将其标记为不同的属性
      differentProperties.push({
        key: diaFormItemEnums[key],
        // eslint-disable-next-line no-prototype-builtins
        oldValue: oldObj.hasOwnProperty(key) ? oldObj[key] : undefined,
        // eslint-disable-next-line no-prototype-builtins
        newValue: newObj.hasOwnProperty(key) ? newObj[key] : undefined,
      })
    }
  }
  // 检查obj2中的属性是否在obj1中不存在
  for (const key in newObj) {
    // eslint-disable-next-line no-prototype-builtins
    if (!oldObj.hasOwnProperty(key)) {
      differentProperties.push({
        key: diaFormItemEnums[key],
        obj1Value: undefined,
        newValue: newObj[key],
      })
    }
  }
  return differentProperties
}

export default {
  data() {
    return {
      diaTitle: '新增',
      formColumns: [
        {
          ele: 'select',
          label: '方案版本号：',
          prop: 'schemeId',
          options: [],
        },
        {
          ele: 'input',
          label: 'ecrf版本号：',
          prop: 'versionNum',
        },
        {
          ele: 'time',
          label: '版本时间：',
          prop: 'versionTime',
        },
        {
          ele: 'textarea',
          label: '备注：',
          prop: 'remark',
        },
      ],
      formData: {
        schemeId: '',
        versionNum: '',
        versionTime: '',
        remark: '',
      },
      defaultFormData: {
        schemeId: '',
        versionNum: '',
        versionTime: '',
        remark: '',
      },
      formRules: {
        // versionNum: [{ required: true, message: '请填写', trigger: 'blur' }],
        versionTime: [{ required: true, message: '请填写', trigger: 'blur' }],
        versionNum: [{ required: true, message: '请填写', trigger: 'blur' }, { validator: this.validatorVersionNum }],
      },
      diaVis: false,
      diaIsAdd: true,
      tableData: [],
      // 编辑时保存原始数据
      editOriginData: {},
      projectId: '',
      projectCode: '',
    }
  },
  created() {
    this.projectId = localStorage.getItem('sys-project-id')
    this.projectCode = localStorage.getItem('sys-project-code')
    this.getListData()
    this.getTableData()
  },
  methods: {
    ...mapActions('solutionVersion', [
      'getSolutionListAPI',
      'addEcrfAPI',
      'getEcrfAPI',
      'updateEcrfAPI',
      'deleteEcrfAPI',
    ]),

    // 版本号表单校验
    validatorVersionNum(rule, userList, callback) {
      const pattern = /^v\d+(\.\d+){0,2}$/

      const flag = userList.match(pattern)
      if (flag) {
        callback()
      } else {
        callback(new Error('请输入正确格式，如v1.0'))
      }
    },

    // 获取方案版本号下拉项数据
    async getListData() {
      const params = {
        projectId: this.projectId,
      }
      const res = await this.getSolutionListAPI({ params })
      if (res.code === 200) {
        this.formColumns[0].options = res.data.map(item => {
          return {
            label: item.versionNum,
            value: item.id,
          }
        })
      }
    },
    // 获取表格数据
    async getTableData() {
      const params = {
        projectId: this.projectId,
      }
      const res = await this.getEcrfAPI({ params })
      if (res.code === 200) {
        this.tableData = res.data
      }
    },

    // 刷新
    handleRefresh() {
      this.getTableData()
    },

    // 点击新增
    handleAdd() {
      this.diaTitle = '新增'
      this.diaVis = true
      this.diaIsAdd = true
    },
    // 点击查看
    handleView(row) {
      this.$router.push({
        path: '/tabModifyHistory',
        query: {
          id: row.id,
          versionNum: row.versionNum,
        },
      })
    },
    // 点击编辑
    handleEdit(row) {
      this.diaTitle = '编辑'
      this.diaVis = true
      this.diaIsAdd = false
      this.formData = {
        ...row,
      }
      this.editOriginData = {
        ...row,
      }
    },
    // 点击删除
    handleDelete(row) {
      this.$confirm('确认删除？', '提示', {
        type: 'warning',
      }).then(async res => {
        const params = {
          id: row.id,
        }
        const result = await this.deleteEcrfAPI({ params })
        if (result.code === 200) {
          this.$message.success('删除成功')
          this.getTableData()
        }
      })
    },
    // 公共关闭逻辑
    publicClose() {
      this.diaVis = false
      this.$refs.formRef.resetFields()
      this.formData = {
        ...this.defaultFormData,
      }
    },
    // 弹窗取消
    handleCancel() {
      this.publicClose()
    },
    // 弹窗确认
    async handleConfirm() {
      await this.$refs.formRef.validate()
      const data = {
        projectId: this.projectId,
        ...this.formData,
      }
      if (this.diaIsAdd) {
        const res = await this.addEcrfAPI({ data })
        if (res.code === 200) {
          this.$message.success('新增成功')
          this.getTableData()
          this.publicClose()
        }
      } else {
        const diffProps = findDifferentProperties(this.editOriginData, this.formData)
        data.historyList = diffProps
        const res = await this.updateEcrfAPI({ data })
        if (res.code === 200) {
          this.$message.success('修改成功')
          this.getTableData()
          this.publicClose()
        }
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.users-base-wrapper {
  background-color: $white;
  height: 100%;
  .user_main_part {
    padding: 12px;
    .solution_table_part {
      margin-top: 24px;
    }
  }
}
</style>
